package com.kira.scaffoldmvc.Test;

import cn.hutool.json.JSONUtil;
import com.kira.scaffoldmvc.POJO.LoginOrRegistry;
import com.kira.scaffoldmvc.POJO.Register;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

public class HttpClientHutoolJsonExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建HttpClient实例
        HttpClient client = HttpClient.newHttpClient();
        Register register=new Register("1657294032@qq.com","492280","Ye");
        // 使用Hutool的JSONUtil将对象转换为JSON字符串
        String jsonBody = JSONUtil.toJsonStr(register);
        System.out.println("请求体JSON字符串: " + jsonBody);

        // 创建HttpRequest实例，设置请求URL、请求方式和请求体
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create("http://47.119.148.251:7000/user/register"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody));

//        // 获取原始请求头并添加到新请求中
//        java.util.Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            String headerValue = httpServletRequest.getHeader(headerName);
//            // 避免覆盖已设置的 Content-Type 头
//            if (!"Content-Type".equalsIgnoreCase(headerName)) {
//                requestBuilder.header(headerName, headerValue);
//            }
//        }

        HttpRequest request = requestBuilder.build();

        // 发送请求并获取响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 处理响应
        System.out.println("响应状态码: " + response.statusCode());
        System.out.println("响应体内容: " + response.body());
        LoginOrRegistry loginOrRegistry = JSONUtil.toBean(response.body(), LoginOrRegistry.class);
        System.out.println(loginOrRegistry);
    }
}